from django.db import models
from django.contrib import admin
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)


class Book(models.Model):
    """
    小说模型
    """
    #假删除过滤选项
    del_choices = (('0', '未删除'),('1', '已删除'))


    #不变信息
    name = models.CharField(max_length=60, verbose_name='小说名', help_text='小说名（CharField）', blank=True,null=True,unique=True)
    url = models.CharField(max_length=200, verbose_name='小说链接', help_text='小说链接（CharField）', blank=True,null=True)

    #模型属性固定字段
    createdBy = models.CharField(max_length=30, verbose_name='创建者', help_text='创建者（CharField）', blank=True)
    createdDate = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', auto_now_add=True,null=True, blank=True)
    lastEditedBy = models.CharField(max_length=30, verbose_name='最后编辑人', help_text='最后编辑人（CharField', blank=True)
    lastEditedDate = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', auto_now=True,null=True, blank=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除（CharField，可选值：0，1）', choices=del_choices, default='0')
    class Meta:
        ordering = ['-id']    #排序
        verbose_name = '小说'            #表示要显示的应用模块的中文名        
        verbose_name_plural = verbose_name #表示已经是复数形式不用再自动加S
    def __str__(self):
        # 返回部门名称
        return self.name 

@admin.register(Book)
class BookAdminModel(admin.ModelAdmin):

    # 添加分页
    list_per_page = 50
    # 列表页展示的字段
    list_display = ('id','name','url','createdBy', 'createdDate', 'lastEditedBy', 'lastEditedDate', 'deleted')
    # 搜索框
    search_fields=('id','name',)